import 'package:flutter/material.dart';
import '../models/period_model.dart';

class CalendarWidget extends StatefulWidget {
  final List<PeriodModel> data;
  final DateTime currentDate;
  final DateTime? selectedDate;
  final Function(DateTime) onDateTap;
  final Function(DateTime)? onMonthChanged;

  final Color? primaryColor;
  final Color? primaryLightColor;
  final Color? secondaryColor;
  final Color? textPrimaryColor;
  final Color? textLightColor;
  final Color? whiteColor;
  final dynamic userProfile;

  const CalendarWidget({
    super.key,
    required this.data,
    required this.currentDate,
    this.selectedDate,
    required this.onDateTap,
    this.onMonthChanged,
    this.primaryColor,
    this.primaryLightColor,
    this.textPrimaryColor,
    this.textLightColor,
    this.userProfile,
    this.secondaryColor = Colors.grey,
    this.whiteColor,
  });

  @override
  State<CalendarWidget> createState() => _CalendarWidgetState();
}

class _CalendarWidgetState extends State<CalendarWidget> {
  late DateTime _currentDisplayMonth;
  final Map<String, List<PeriodModel>> _monthDataCache = {};
  static const int _maxCacheMonths = 6;
  late ScrollController _scrollController;
  // 移除未使用的缓存字段
  bool _isLoading = false;
  final bool _debugMode = true;
  late Color predictedPeriodColor;
  late Color predictedOvulationPeriodColor;
  late Color ovulationDayColor;
  late Color selectedDateColor;
  late Color todayBorderColor;
  late Color textPrimaryColor;
  late Color textLightColor;
  late Color backgroundColor;

  @override
  void initState() {
    super.initState();
    try {
      _isLoading = true;
      _currentDisplayMonth = DateTime(widget.currentDate.year, widget.currentDate.month, 1);
      _scrollController = ScrollController();
      _initializeColors();
      _updateMonthDataCache();
      
      // 预加载相邻月份数据
      Future.microtask(() {
        _preloadAdjacentMonths();
      });
    } catch (e) {
      if (_debugMode) {
        debugPrint('Error in initState: $e');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _initializeColors() {
    predictedPeriodColor = widget.primaryLightColor ?? Colors.red.shade100;
    predictedOvulationPeriodColor = widget.primaryColor ?? Colors.blue.shade200;
    ovulationDayColor = widget.primaryColor ?? Colors.blue.shade500;
    selectedDateColor = widget.primaryColor ?? Colors.blue.shade500;
    todayBorderColor = widget.primaryColor ?? Colors.blue.shade500;
    textPrimaryColor = widget.textPrimaryColor ?? Colors.black;
    textLightColor = widget.textLightColor ?? Colors.grey;
    backgroundColor = widget.whiteColor ?? Colors.white;
  }

  void _updateMonthDataCache() {
    // 清空现有缓存，确保数据一致性
    _monthDataCache.clear();
    
    for (var period in widget.data) {
      _updateMonthDataCacheForPeriod(period);
    }
    
    // 清理过多的缓存数据
    _cleanupOldCacheData();
  }

  void _updateMonthDataCacheForPeriod(PeriodModel period) {
    // 确保每个经期数据被添加到正确的月份缓存中
    final monthKey = _getMonthKey(period.date);
    _monthDataCache.putIfAbsent(monthKey, () => []);
    
    // 避免重复添加相同的日期数据
    final existingIndex = _monthDataCache[monthKey]!.indexWhere(
      (p) => _isDateInPeriod(p.date, period),
    );
    
    if (existingIndex >= 0) {
      // 如果已存在，更新数据
      _monthDataCache[monthKey]![existingIndex] = period;
    } else {
      // 否则添加新数据
      _monthDataCache[monthKey]!.add(period);
    }
  }

  void _updateMonthDataCacheForMonth(DateTime month) {
    // 实现月份数据更新逻辑
    final monthKey = _getMonthKey(month);
    
    // 确保缓存中存在该月份的数据
    if (!_monthDataCache.containsKey(monthKey)) {
      _monthDataCache[monthKey] = [];
    } else {
      // 清空现有数据，重新加载以确保数据最新
      _monthDataCache[monthKey]!.clear();
    }
    
    // 从widget.data中筛选出当前月份的数据
    for (var period in widget.data) {
      if (_isPeriodInMonth(period, month)) {
        _monthDataCache[monthKey]!.add(period);
      }
    }
    
    // 预加载相邻月份的数据，确保跨月显示正常
    _preloadAdjacentMonths();
  }

  bool _isPeriodInMonth(PeriodModel period, DateTime month) {
    return period.date.year == month.year && period.date.month == month.month;
  }

  List<PeriodModel> _getMonthData(DateTime month) {
    final monthKey = _getMonthKey(month);
    return _monthDataCache[monthKey] ?? [];
  }

  String _getMonthKey(DateTime date) {
    return '${date.year}-${date.month}';
  }

  void _preloadAdjacentMonths() {
    for (int i = -2; i <= 2; i++) {
      final monthToLoad = DateTime(
        _currentDisplayMonth.year,
        _currentDisplayMonth.month + i,
        1,
      );
      _updateMonthDataCacheForMonth(monthToLoad);
    }
  }

  void _cleanupOldCacheData() {
    // 保持缓存的大小在合理范围内
    if (_monthDataCache.length > _maxCacheMonths) {
      // 计算需要保留的月份
      final keysToKeep = <String>{};
      for (int i = -2; i <= 2; i++) {
        final month = DateTime(
          _currentDisplayMonth.year,
          _currentDisplayMonth.month + i,
          1,
        );
        keysToKeep.add(_getMonthKey(month));
      }
      
      // 移除不需要的缓存
      final keysToRemove = _monthDataCache.keys.where((key) => !keysToKeep.contains(key)).toList();
      for (var key in keysToRemove) {
        _monthDataCache.remove(key);
      }
    }
  }

  void _handleMonthChange(DateTime newMonth) {
    if (mounted) {
      setState(() {
        _isLoading = true;
      });
    }
    
    _currentDisplayMonth = newMonth;
    
    // 确保当前月份和相邻月份的数据都被正确加载
    _updateMonthDataCacheForMonth(newMonth);
    
    // 通知外部月份变化
    if (widget.onMonthChanged != null) {
      widget.onMonthChanged!(newMonth);
    }
    
    // 延迟一小段时间后更新UI，避免频繁刷新
    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    });
  }

  // _switchToMonth 方法已与 _handleMonthChange 合并

  void _handleHorizontalDrag(DragEndDetails details) {
    final velocity = details.primaryVelocity ?? 0;
    const double swipeThreshold = 1000.0;
    
    if (velocity.abs() > swipeThreshold) {
      if (velocity < 0) {
        final nextMonth = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month + 1, 1);
        _handleMonthChange(nextMonth);
      } else {
        final prevMonth = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month - 1, 1);
        _handleMonthChange(prevMonth);
      }
    }
  }

  List<Widget> _buildCalendarGrid() {
    try {
      final List<Widget> rows = [];
      final monthData = _getMonthData(_currentDisplayMonth);
      
      // 生成月份的第一天和最后一天
      final firstDay = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month, 1);
      final lastDay = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month + 1, 0);
      
      // 获取第一天是星期几（1-7，1是星期一）
      // 将星期一作为第一天，转换为0-6的索引，0是星期一
      final firstDayWeekday = (firstDay.weekday - 1) % 7;
      
      // 添加星期标题
      rows.add(_buildWeekdayRow());
      
      // 计算需要显示的行数（确保显示完整的日历网格）
      const int daysPerWeek = 7;
      final int totalDaysInGrid = firstDayWeekday + lastDay.day;
      final int totalWeeks = (totalDaysInGrid + daysPerWeek - 1) ~/ daysPerWeek;
      
      // 生成日期网格
      for (int week = 0; week < totalWeeks; week++) {
        List<Widget> currentRow = [];
        
        for (int dayOfWeek = 0; dayOfWeek < daysPerWeek; dayOfWeek++) {
          final int dayIndex = week * daysPerWeek + dayOfWeek;
          final int dayOffset = dayIndex - firstDayWeekday + 1;
          
          DateTime? currentDate;
          if (dayOffset > 0 && dayOffset <= lastDay.day) {
            // 当前月的日期
            currentDate = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month, dayOffset);
          } else if (dayOffset <= 0) {
            // 上个月的日期
            final prevMonth = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month, 0);
            final prevMonthDay = prevMonth.day + dayOffset;
            currentDate = DateTime(prevMonth.year, prevMonth.month, prevMonthDay);
          } else {
            // 下个月的日期
            currentDate = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month + 1, dayOffset - lastDay.day);
          }
          
          currentRow.add(_buildDateCell(currentDate, monthData));
        }
        
        rows.add(Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: currentRow,
        ));
      }
      
      return rows;
    } catch (e) {
      if (_debugMode) {
        debugPrint('Error in _buildCalendarGrid: $e');
      }
      return [Container(color: Colors.grey.shade100, height: 200, child: Center(child: Text('加载错误')))];
    }
  }

  Widget _buildWeekdayRow() {
    final weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: weekdays.map((day) => Expanded(
        child: Text(
          day,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: textLightColor,
            fontSize: 14,
          ),
        ),
      )).toList(),
    );
  }

  Widget _buildDateCell(DateTime date, List<PeriodModel> monthData) {
    // 实现日期单元格的构建逻辑
    final bool isCurrentMonth = date.year == _currentDisplayMonth.year && date.month == _currentDisplayMonth.month;
    final bool isSelected = widget.selectedDate != null && 
                           date.year == widget.selectedDate!.year &&
                           date.month == widget.selectedDate!.month &&
                           date.day == widget.selectedDate!.day;
    final bool isToday = date.year == DateTime.now().year &&
                        date.month == DateTime.now().month &&
                        date.day == DateTime.now().day;
    
    Color cellColor = Colors.transparent;
    
    // 查找当前日期对应的周期数据
    PeriodModel? matchingPeriod;
    if (isCurrentMonth) {
      matchingPeriod = _findMatchingPeriod(date, monthData);
    } else {
      // 对于非当前月，也需要查找匹配的周期数据以正确显示标记
      matchingPeriod = _findMatchingPeriod(date, _getAllPeriodData());
    }
    
    // 根据匹配的周期数据设置颜色
    if (matchingPeriod != null) {
      // 设置颜色优先级：实际经期 > 排卵日 > 预测经期 > 可能经期
      if (matchingPeriod.isPeriod) {
        cellColor = predictedPeriodColor; // 使用相同的颜色表示实际和预测经期
      } else if (matchingPeriod.isOvulation) {
        cellColor = ovulationDayColor;
      } else if (matchingPeriod.isPredictedPeriod) {
        cellColor = predictedPeriodColor;
      } else if (matchingPeriod.isPossiblePeriod) {
        // 为可能的经期设置一个不同的颜色
        cellColor = Colors.red.shade50;
      }
    }
    
    // 选中日期的样式应该覆盖其他样式
    Color textColor = isCurrentMonth ? textPrimaryColor : textLightColor.withAlpha(128);
    if (isSelected) {
      textColor = Colors.white;
      cellColor = selectedDateColor;
    }
    
    return Expanded(
      child: GestureDetector(
        onTap: isCurrentMonth ? () => widget.onDateTap(date) : null,
        child: Container(
          height: 40,
          margin: EdgeInsets.all(2),
          decoration: BoxDecoration(
            color: cellColor,
            borderRadius: BorderRadius.circular(20),
            border: isToday ? Border.all(color: todayBorderColor, width: 2) : null,
          ),
          alignment: Alignment.center,
          child: Text(
            '${date.day}',
            style: TextStyle(
              color: textColor,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ),
      ),
    );
  }
  
  PeriodModel? _findMatchingPeriod(DateTime date, List<PeriodModel> periodData) {
    try {
      return periodData.firstWhere(
        (period) => _isDateInPeriod(date, period),
      );
    } catch (e) {
      // 没有找到匹配的日期时返回null
      return null;
    }
  }
  
  List<PeriodModel> _getAllPeriodData() {
    // 获取所有缓存月份的周期数据
    final allData = <PeriodModel>[];
    for (var monthData in _monthDataCache.values) {
      allData.addAll(monthData);
    }
    return allData;
  }

  bool _isDateInPeriod(DateTime date, PeriodModel period) {
    // 直接比较日期是否匹配，因为PeriodModel使用单个date属性
    return date.year == period.date.year && 
           date.month == period.date.month && 
           date.day == period.date.day;
  }

  Widget _buildMonthNavigationBar() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        IconButton(
          icon: Icon(Icons.chevron_left),
          onPressed: () {
            final prevMonth = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month - 1, 1);
            _handleMonthChange(prevMonth);
          },
        ),
        Text(
          '${_currentDisplayMonth.year}年${_currentDisplayMonth.month}月',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        IconButton(
          icon: Icon(Icons.chevron_right),
          onPressed: () {
            final nextMonth = DateTime(_currentDisplayMonth.year, _currentDisplayMonth.month + 1, 1);
            _handleMonthChange(nextMonth);
          },
        ),
      ],
    );
  }

  Widget _buildLoadingIndicator() {
    return Expanded(
      child: Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    _initializeColors();
    
    return Container(
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(12),
      ),
      padding: EdgeInsets.all(16),
      child: GestureDetector(
        onHorizontalDragEnd: _handleHorizontalDrag,
        child: Column(
          children: <Widget>[
            _buildMonthNavigationBar(),
            SizedBox(height: 10),
            _isLoading ? _buildLoadingIndicator() : Expanded(
              child: SingleChildScrollView(
                controller: _scrollController,
                child: Column(
                  children: _buildCalendarGrid(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}